package jp.co.dailyReport;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.struts.action.*;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.staff.StaffManager;

/**
 * 業務管理ｼｽﾃﾑ認証ページの「ログイン」ボタン
 * が押されたときの処理を管理するクラスです。
 */
public class LoginAction extends Action {

	private static Logger log = Logger.getLogger(LoginAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
	 throws IOException, ServletException {

		log.debug("LoginAction start");
		HttpSession session = request.getSession();
		LoginActionForm loginActionForm = (LoginActionForm)form;
		String target = "success";
		ActionErrors errors = new ActionErrors();

		try {
			session.removeAttribute("LoginStaff");
			if(!StaffManager.isExist(loginActionForm.getUsr())) {
				target = "false";
				errors.add("usr", new ActionError("errors.usr.unknown"));
			} else {
				Staff staff = StaffManager.load(loginActionForm.getUsr());
				String keyCode = staff.getKeyCode();
				if(!keyCode.equals(StaffManager.encryptedPassword(loginActionForm.getPasswd()))) {
					target = "false";
					errors.add("passwd", new ActionError("errors.passwd.unknown"));
				} else {
					staff.setKeyCode(keyCode);
					session.setAttribute("LoginStaff", staff);
				}
			}
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}
		if(!errors.isEmpty())
		 saveErrors(request, errors);
		log.debug("LoginAction end");
		return mapping.findForward(target);
	}
}
